<template>
  <div class="can-container menu" v-loading="loading">
    <el-button
      type="primary"
      size="small"
      icon="el-icon-plus"
      class="addBtn"
      @click="handleNewAddLevelOne"
      >新增</el-button
    >
    <el-tree
      :data="menuData"
      :props="defaultProps"
      node-key="id"
      @check="handleCheckChange"
      default-expand-all
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <el-badge :is-dot="data.ifHomeShow == 'YES'">{{ node.label }}</el-badge>
        <div style="float: right; width: 300px">
          <el-badge :value="data.orders" type="primary"></el-badge>
          <el-button
            type="primary"
            size="mini"
            v-if="node.level <= 3"
            @click="() => handleNewAdd(node, data)"
            >新增</el-button
          >
          <el-button
            type="warning"
            size="mini"
            v-if="handelNodeLevel(node, data)"
            @click="() => handleTag(node, data)"
            >{{ data.ifHomeShow == "YES" ? "取消标志" : "标志" }}</el-button
          >
          <el-button
            type="success"
            size="mini"
            @click="() => handleEditeMenu(node, data)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="() => handleRemoveMenu(node, data)"
            >删除</el-button
          >
        </div>
        <!-- <el-popover placement="right" trigger="hover">
          <span></span>
          <i class="el-icon-more" style="font-size: 20px;" slot="reference"></i>
        </el-popover>-->
      </span>
    </el-tree>
    <!-- 菜单新增页面 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="400px"
      @close="handleReset"
    >
      <div>
        <el-form label-width="90px" :model="formData" ref="formData">
          <el-form-item label="菜单名称" prop="name">
            <el-input style="width:230px" v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="链接URL" prop="url">
            <el-input style="width:230px" v-model="formData.url"></el-input>
          </el-form-item>
          <el-form-item label="标识KEY" prop="key">
            <el-input style="width:230px" v-model="formData.key"></el-input>
          </el-form-item>
          <el-form-item label="菜单排序" prop="orders">
            <el-input
              style="width:230px"
              type="number"
              v-model="formData.orders"
            ></el-input>
          </el-form-item>
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="formData.type">
              <el-radio-button label="REAL">有效</el-radio-button>
              <el-radio-button label="VIRTUAL">无效</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单图标" prop="icoId">
            <el-upload
              :action="uploadUrl"
              :headers="headers"
              list-type="picture-card"
              :limit="1"
              :on-success="handleUploadSuccess"
              :file-list="fileList"
              accept=".png, .jpg, .jpeg"
              :on-exceed="uploadExceed"
              ref="uploadIcon"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="text-center">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMenuData,
  newAddMenu,
  updateMenu,
  deleteData,
  detailByID,
  tagCommonType
} from "@/api/project/system/menu.js";
import config from "@/config/index.js";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      uploadUrl: config.baseUrlImg + "/pc/file/upload",
      headers: {
        authorization: getToken()
      },
      formData: {
        name: "",
        url: "",
        key: "",
        orders: 1,
        type: "REAL",
        icoId: ""
      },
      menuData: [],
      defaultProps: {
        label: "name"
      },
      dialogTitle: "菜单管理_新增",
      dialogVisible: false,
      menuDetail: {}, //保存弹框信息菜单
      fileList: [],
      submitType: 0, //0:新增；1：编辑
      handelNodeLevel: function(node, data) {
        if ("children" in data) {
          return false;
        } else {
          return true;
        }
      },
      loading: false
    };
  },
  methods: {
    getInitData: function() {
      this.handleGetMenuData();
    },
    //获取所有菜单列表数据
    handleGetMenuData: function() {
      this.loading = true;
      getMenuData()
        .then(res => {
          this.loading = false;
          //返回数据处理
          let data = res.data;
          this.menuData = this.menuHandle(data);
        })
        .catch(err => {
          this.loading = false;
        });
    },
    //菜单数据处理
    menuHandle: function(data) {
      let result = [];
      if (!Array.isArray(data)) {
        return result;
      }
      data.forEach(item => {
        delete item.children;
      });
      let map = {};
      data.forEach(item => {
        map[item.id] = item;
      });
      data.forEach(item => {
        let parent = map[item.parentId];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      result.sort((a, b) => {
        return b.orders - a.orders;
      });
      return result;
    },
    //图标上传成功回调
    handleUploadSuccess: function(res, file, fileList) {
      this.formData["icoId"] = res.data.id;
    },
    //一级新增
    handleNewAddLevelOne: function() {
      this.dialogVisible = true;
      this.formData["parentId"] = 0;
      this.dialogTitle = "菜单管理_新增";
      this.submitType = 0;
    },
    //二级新增
    handleNewAdd: function(node, data) {
      this.menuDetail = data;
      this.formData["parentId"] = data.id;
      this.dialogVisible = true;
      this.dialogTitle = "菜单管理_新增";
      this.submitType = 0;
    },
    //修改
    handleEditeMenu: function(node, data) {
      this.dialogVisible = true;
      this.dialogTitle = "菜单管理_编辑";
      this.submitType = 1;
      let params = {
        id: data.id
      };
      detailByID(params).then(res => {
        this.formData = res.data;
        let file = {
          name: res.data.icoDto.fileName,
          url: config.baseUrlImg + res.data.icoDto.filePath
        };
        this.fileList = [file];
      });
    },
    //新增、修改提交确定
    handleSubmit: function() {
      if (this.submitType == 0) {
        newAddMenu(this.formData).then(res => {
          this.$message.success("操作成功！");
          this.handleGetMenuData();
          this.dialogVisible = false;
        });
      } else {
        updateMenu(this.formData).then(res => {
          this.$message.success("操作成功！");
          this.handleGetMenuData();
          this.dialogVisible = false;
        });
      }
    },
    //重置
    handleReset: function() {
      this.$refs["formData"].resetFields();
      this.$refs["uploadIcon"].clearFiles();
    },
    //删除
    handleRemoveMenu: function(node, data) {
      this.$confirm("此操作将删除此菜单，是否继续", "提示！", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(res => {
        let params = {
          id: data.id
        };
        deleteData(params).then(res => {
          this.$message.success("操作成功！");
          this.handleGetMenuData();
        });
      });
    },
    handleCheckChange: function(data, data1, data2) {
      console.log(data, data1, data2);
    },
    //图标个数超出回调
    uploadExceed: function() {
      this.$message.error("超出上传个数，请先删除后上传！");
    },
    //菜单做常用标记处理
    handleTag: function(node, data) {
      let params = {
        id: data.id,
        state: data.ifHomeShow == "YES" ? "NO" : "YES"
      };
      tagCommonType(params).then(res => {
        this.$message.success("操作成功！");
        this.handleGetMenuData();
      });
    }
  },
  created() {
    this.getInitData();
  }
};
</script>

<style lang="scss" scoped>
.can-container.menu .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding: 20px;
}
.can-container.menu /deep/ .el-tree-node__content {
  height: 48px;
}
</style>

<style lang="scss" scoped>
.can-container /deep/ .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
}
.can-container /deep/ .el-upload--picture-card i {
  font-size: 15px;
}
.can-container /deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
}
</style>

<style lang="scss" scoped>
.can-container {
  padding: 20px;
  background: #fff;
  .addBtn {
    margin-bottom: 20px;
  }
}
</style>
